package com.invengo.library_rfid.analyze.impl;


import com.invengo.library_rfid.analyze.ConvertUtil;
import com.invengo.library_rfid.analyze.EPCStrategy;
import com.invengo.library_rfid.analyze._EpcRuleTag;

import java.io.Serializable;

public class BenBuEPCStrategyImpl implements EPCStrategy ,Serializable{
    @Override
    public _EpcRuleTag getRule() {
        return _EpcRuleTag.RULE_BenBu;
    }

    @Override
    public String analyzeShelf(String epc) {
        return analyzeBook(epc);
    }


    // : 2023/9/28 很蠢的处理方式
    @Override
    public String analyzeBook(String epc) {
        String binstr = ConvertUtil.str16ToStr2(epc);
        String tag = binstr.substring(0, 4);
        String type = binstr.substring(4, 8);
        String hexTag = ConvertUtil.str2ToStr16(type);
        int decLength = Integer.parseInt(binstr.substring(8, 16), 2);
        String substring = epc.substring(4, decLength * 4 + 4);
        String binaryString = hex2bin(substring);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < binaryString.length() / 6; i++) {
            sb.append(bin2dec(binaryString.substring(i * 6, i * 6 + 6)));
        }
        return sb.toString();
    }

    public static String hex2bin(String input) {
        StringBuilder sb = new StringBuilder();
        int len = input.length();
//        System.out.println("原数据长度：" + (len / 2) + "字节");
        for (int i = 0; i < len; i++) {
            //每1个十六进制位转换为4个二进制位
            String temp = input.substring(i, i + 1);
            int tempInt = Integer.parseInt(temp, 16);
            String tempBin = Integer.toBinaryString(tempInt);
            //如果二进制数不足4位，补0
            if (tempBin.length() < 4) {
                int num = 4 - tempBin.length();
                for (int j = 0; j < num; j++) {
                    sb.append("0");
                }
            }
            sb.append(tempBin);
        }
        return sb.toString();
    }


    /**
     * 6位2进制转10进制
     */
    private String bin2dec(String binstr) {
        switch (binstr) {
            case "000010":
                return "B";
            case "000001":
                return "A";
            case "011011":
                return "0";
            case "011100":
                return "1";
            case "011101":
                return "2";
            case "011110":
                return "3";
            case "011111":
                return "4";
            case "100000":
                return "5";
            case "111011":
                return "6";
            case "111100":
                return "7";
            case "111101":
                return "8";
            case "111110":
                return "9";
            default:
                return "-1";
        }
    }
}
